#!/bin/bash
function install_php() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装PHP${nocolor}"
    echo -e "${blue}如果你有安装Apache的打算,${nocolor} ${green}建议优先安装Apache${nocolor}"
    echo ""
    phpPid=`pidof php-fpm`
    if [ -n "$phpPid" ];then
        echo -e "$Error 系统中已经有PHP在运行，请先卸载！！！"
        anykeyback
        return 1
    fi
    
    phpHome="$workHome/packages/php"
    cd $phpHome
    while [[ ! ${phpVer_digit} =~ ^[0-9]+$ || "$php_dot" == "0" || "$php_endwith" == "." ]]
    do
        echo -ne "输入需要安装的PHP版本[7.4.5], 列出推荐版本[Hh]: "
        read phpVer
        phpVer=${phpVer:-7.4.5}
        phpVer=`echo $phpVer`

        phpVer_digit=${phpVer//./}
        php_dot=$(echo $phpVer|grep -o "\."|wc -l)
        php_endwith=${phpVer:0-1}
        phpVer_=${phpVer^^}
        
        if [[ ${phpVer_} =~ H[0-9]*$ ]];then
            if [ "$die_network" == "ture" ];then
                    echo -e "$Info 设备未联网，不支持查询"
            else
                show_lines=$(echo $phpVer|egrep -o "[0-9]*"|head -n1)
                if [ "X$show_lines" == "X" ];then
                    show_lines=10
                fi
                echo -e "$Info PHP推荐稳定版本"
                curl --connect-timeout 30 -m 65 -s https://www.php.net/releases/index.php?json|grep -Eo "PHP [1-9]\.[0-9]+\.[0-9]+"|awk '{print $2}'|sort -urV|head -n${show_lines}
            fi
        else
            if [[ ! ${phpVer_digit} =~ ^[0-9]+$ || "$php_dot" == "0" || "$php_endwith" == "." ]];then
                echo -e "$Warn PHP版本号只能由数字和.组成，且不以.结尾，请重新输入！"
                sleep 0.5
            fi    
        fi
    done
    echo ""
    
    if [ ! -f $phpHome/php-$phpVer.tar.bz2 -a "$die_network" == "ture" ];then
        echo -e "$Error 系统未联网，且本地不存在需要安装的PHP版本！！！"
        anykeyback
        return 1
    fi
    
    mainPhpVer=`echo $phpVer|awk -F"." '{print $1}'`
    subPhpVer=`echo $phpVer|awk -F"." '{print $2}'`
    
    
    echo -ne "输入PHP安装位置[/usr/local/php$mainPhpVer]: "
    read -e phpPath
    phpPath=${phpPath:-/usr/local/php$mainPhpVer}
    phpPath=`echo ${phpPath}`
    phpPath=${phpPath%/}
    echo ""
    
    isNull=`ls $phpPath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        echo -ne "PHP安装目录非空，继续安装会删除已有数据！\n继续[Yy,Enter],退出[Nn]: "
        read isYn
        if [[ $isYn == [Nn] ]];then
          sleep 0.5
          return 1
        fi
        echo ""
    fi
  
    AapacheSupport=""
    echo -ne "为Apache添加PHP支持(${blue}需已安装Apache${nocolor})，添加[Yy,Enter],不添加[Nn]: "
    read isAdd
    if [[ $isAdd != [Nn] ]];then
        echo ""
        echo -ne "输入Apache apxs文件位置，一般位于apache安装目录bin文件夹\n请输入[/usr/local/apache2/bin/apxs]: "
        read -e apxsPath
        apxsPath=${apxsPath:-/usr/local/apache2/bin/apxs}
        apxsPath=`echo $apxsPath`
        while [ ! -f "$apxsPath" ]
        do
            echo -ne "$Warn 指定位置未找到apxs，请重新输入，不添加支持[Nn]: "
            read -e apxsPath
            apxsPath=`echo $apxsPath`
            if [ "${apxsPath^^}" == "N" ];then
                apxsPath="GIVEUP"
                break
            fi
        done
        if [ "${apxsPath}" == "GIVEUP" ];then
            apacheadd="No"
            echo ""
        else
            AapacheSupport="--with-apxs2=$apxsPath"
            apachePath=${apxsPath%/bin*}
            apacheadd="Yes"
            echo ""
        fi
    else
        apacheadd="No"
        echo ""
    fi
    
    
    phpInfo_sum_head="${blue}PHP安装信息汇总${nocolor}
---------------------------------
PHP版本：$phpVer
PHP安装位置：$phpPath
Apache扩展支持：$apacheadd"

    phpInfo_sum_end="---------------------------------
继续[Yy,Enter],退出[Nn]: "
    
    if [ "$apacheadd" == "Yes" ];then
        phpInfo_sum="${phpInfo_sum_head}
apxs文件位置：${apxsPath}
Apache安装位置: $apachePath
${phpInfo_sum_end}"
    else
        phpInfo_sum="${phpInfo_sum_head}
${phpInfo_sum_end}"
    fi
    
    echo -ne "${phpInfo_sum}"
    read isYn
    [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
    
    echo ""
    echo -e "${cyan}将开始PHP安装过程${nocolor}"
    echo ""
    if [ "$die_network" == "true" ];then
        ping -c 2 -w 5 180.76.76.76 >/dev/null 2>&1
        if [ "$?" != "0" ];then
           die_network="true"
        else
           die_network="false"
        fi
    fi
    if [[ ! -f $phpHome/php-$phpVer.tar.bz2 && "$die_network" == "false" ]];then
        echo -e "$Info ${purple}下载PHP安装包${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 600 --fail -O https://www.php.net/distributions/php-$phpVer.tar.bz2
        if [ "$?" != "0" ];then
           rm -rf $phpHome/php-$phpVer.tar.bz2
           echo -e "$Info ${purple}尝试使用wget下载${nocolor}"
           wget -t5 https://www.php.net/distributions/php-$phpVer.tar.bz2
        fi
                
        if [ "$?" != "0" ];then
           echo -e "$Error 下载PHP失败，请检查网络或者不存在此版本的PHP，退出！！！"
           anykeyback
           return 1
        fi
    elif [[ ! -f $phpHome/php-$phpVer.tar.bz2 && "$die_network" == "true" ]];then
        echo -e "$Error 你的主机未联网，请提前手动下载安装包，使用离线安装！！！"
        anykeyback
        return 1
    fi
    
    echo -e "$Info ${purple}添加EPEL YUM源$nocolor"
    if [ "$system_ver" == "6" ];then
          curl -so /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
    elif [ "$system_ver" == "7" ];then
          curl -so /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    elif [ "$system_ver" == "8" ];then
          yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm
          sed -i 's|^#baseurl=https://download.fedoraproject.org/pub|baseurl=https://mirrors.aliyun.com|' /etc/yum.repos.d/epel*
          sed -i 's|^metalink|#metalink|' /etc/yum.repos.d/epel*
    fi
    
    echo -e "$Info ${purple}安装所需基础RPM包${nocolor}"
    yum -y install glib2 glib2-devel make gcc gcc-c++ cmake curl curl-devel ncurses ncurses-devel perl \
    pcre-devel wget unzip glibc glibc-devel openssl libaio-devel autoconf automake  libxml*  \
    libtool-ltdl-devel* libxml2 libxml2-devel openssl-devel libcurl-devel libjpeg libjpeg-devel libjpeg-turbo* libpng \
    libpng-devel libicu-devel openldap openldap-devel gd gd-devel php-gd  bzip2 bzip2-devel freetype \
    freetype-devel bison bison-devel zlib zlib-devel libmcrypt-devel mcrypt mhash-devel readline-devel \
    libedit-devel sqlite-devel libidn libidn-devel jq oniguruma oniguruma-devel openldap.i686 openldap-devel.i686
    if [ "$?" != "0" ];then
        echo -e "$Error 基础依赖软件安装失败，退出安装！！！"
        anykeyback
        return 1
    fi
    
    for i in glib2 glib2-devel make gcc gcc-c++ cmake curl ncurses ncurses-devel perl \
    pcre-devel wget unzip glibc glibc-devel openssl libaio-devel autoconf automake    \
     libxml2 libxml2-devel openssl-devel libcurl-devel libpng \
    libpng-devel libicu-devel openldap openldap-devel gd gd-devel php-gd  bzip2 bzip2-devel freetype \
    freetype-devel bison bison-devel zlib zlib-devel libmcrypt-devel mcrypt mhash-devel readline-devel \
    libedit-devel sqlite-devel libidn libidn-devel oniguruma oniguruma-devel
    do
        rpm -q $i >/dev/null 2>&1
        if [ "$?" != "0" ];then
            echo -e "$Error 基础依赖软件${i}安装失败，退出安装!"
            anykeyback
            return 1
        fi
    done
    
    find $phpHome/* -type d|xargs rm -rf
    echo ""
    
    echo -e "${blue}安装libzip${nocolor}"
    cd $phpHome
    if [ ! -f libzip-1.3.2.tar.gz ];then
        echo -e "$Info ${purple}下载libzip${nocolor}"
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://libzip.org/download/libzip-1.3.2.tar.gz
    fi
    if [ "$?" != "0" ];then
        rm -rf libzip-1.3.2.tar.gz
        curl --progress-bar --connect-timeout 30 -m 360 --fail -O https://libzip.org/download/libzip-1.3.2.tar.gz
    fi
    echo -e "$Info ${purple}解压libzip${nocolor}"
    tar zxf libzip-1.3.2.tar.gz && cd libzip-1.3.2 && \
    echo -e "$Info ${purple}预编译libzip${nocolor}"
    ./configure && \
    echo -e "$Info ${purple}编译libzip${nocolor}" && \
    make && \
    echo -e "$Info ${purple}安装libzip${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装libzip失败，退出安装！！！"
        anykeyback
        return 1
    fi
    sed -i "/export PKG_CONFIG_PATH=/d" ~/.bashrc
    echo "export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig/:/usr/local/lib64/pkgconfig/:/lib/pkgconfig/:/lib64/pkgconfig/"" >> ~/.bashrc
    source ~/.bashrc
    export PKG_CONFIG_PATH="/usr/local/lib/pkgconfig/:/usr/local/lib64/pkgconfig/:/lib/pkgconfig/:/lib64/pkgconfig/"
    echo ""
    
    echo -e "${blue}安装PHP${nocolor}"
    cd $phpHome
    echo ""
    if [[ "$mainPhpVer" -le "5" ]];then
        phpConfigure="./configure --prefix=$phpPath --with-config-file-path=$phpPath/etc ${AapacheSupport} --with-mysql --with-pdo-mysql --with-mysqli --with-mysql-sock --with-gd --with-iconv --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-bz2 --with-libxml-dir --enable-xml --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --enable-ftp --enable-gd-native-ttf --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --with-pear --with-gettext --enable-session --with-mcrypt --with-mhash --enable-fpm --with-ldap"
    elif [[ "$mainPhpVer" -eq "7" ]];then
        if [[ "$subPhpVer" -le "1" ]];then
           phpConfigure="./configure --prefix=$phpPath --with-config-file-path=$phpPath/etc $AapacheSupport --with-pdo-mysql --with-mysqli --with-mysql-sock --with-gd --with-iconv --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-bz2 --with-libxml-dir --enable-xml --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --enable-ftp --enable-gd-native-ttf --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --with-pear --with-gettext --enable-session --with-mcrypt --with-mhash --enable-fpm --with-ldap"
        elif [[ "$subPhpVer" -le "3" ]];then
           phpConfigure="./configure --prefix=$phpPath --with-config-file-path=$phpPath/etc $AapacheSupport --with-pdo-mysql --with-mysqli --with-mysql-sock --with-gd --with-iconv --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-bz2 --with-libxml-dir --enable-xml --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --enable-ftp --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --with-pear --with-gettext --enable-session --with-mhash --enable-fpm --with-ldap"
        else
           phpConfigure="./configure --prefix=$phpPath --with-config-file-path=$phpPath/etc $AapacheSupport --with-pdo-mysql --with-mysqli --with-mysql-sock --enable-gd --with-iconv --with-freetype --with-jpeg --with-zlib --with-bz2 --enable-xml --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --enable-ftp --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --with-zip --enable-soap --with-pear --with-gettext --enable-session --enable-fpm --with-ldap"
        fi
    else
        phpConfigure="./configure --prefix=$phpPath --with-config-file-path=$phpPath/etc $AapacheSupport --with-pdo-mysql --with-mysqli --with-mysql-sock --enable-gd --with-iconv --with-freetype --with-jpeg --with-zlib --with-bz2 --enable-xml --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-mbstring --enable-ftp --with-openssl --enable-pcntl --enable-sockets --with-xmlrpc --with-zip --enable-soap --with-pear --with-gettext --enable-session --enable-fpm --with-ldap"    
    fi
    echo -e "$Info ${purple}解压PHP${nocolor}"
    tar jxf php-${phpVer}.tar.bz2 && cd php-${phpVer} && \
    echo -e "$Info ${purple}预编译PHP${nocolor}" && \
    $phpConfigure && \
    echo -e "$Info ${purple}编译PHP${nocolor}" && \
    make -j8 && \
    echo -e "$Info ${purple}安装PHP${nocolor}" && \
    make install
    if [ "$?" != "0" ];then
        echo -e "$Error 安装PHP失败，退出安装！！！"
        anykeyback
        return 1
    fi
    echo ""
    
    echo -e "$Info ${purple}配置PHP${nocolor}"
    /bin/cp -f $phpPath/etc/php-fpm.conf.default $phpPath/etc/php-fpm.conf
    sed -i 's/;pid = run\/php-fpm.pid/pid = run\/php-fpm.pid/' $phpPath/etc/php-fpm.conf
    sed -i 's/;error_log = log\/php-fpm.log/error_log = log\/php-fpm.log/' $phpPath/etc/php-fpm.conf
    /bin/cp $phpPath/etc/php-fpm.d/www.conf.default $phpPath/etc/php-fpm.d/www.conf >/dev/null 2>&1
    
    echo -e "$Info ${purple}禁止显示PHP版本,设置时区,开启PHP短标签支持${nocolor}"
    /bin/cp -f php.ini-production $phpPath/etc/php.ini
    sed -i 's/expose_php = On/expose_php = Off/' $phpPath/etc/php.ini
    sed -i 's/short_open_tag = Off/short_open_tag = On/' $phpPath/etc/php.ini
    sed -i 's/;date.timezone =/date.timezone = PRC/' $phpPath/etc/php.ini
  
    rm -rf /etc/php.ini
    ln -sf $phpPath/etc/php.ini /etc/php.ini  
   
    echo -e "$Info ${purple}启动php-fpm并设置开机启动${nocolor}"
    /bin/cp -f sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm
    chmod +x /etc/rc.d/init.d/php-fpm
    service php-fpm start
    /sbin/chkconfig php-fpm on
    
    echo -e "$Info ${purple}重新加载apache配置，以启用PHP扩展${nocolor}"
    if [ -n "$apachePath" ];then
        $apachePath/bin/apachectl -k graceful
    fi
    echo ""
    
    phpPid=`pidof php-fpm`
    if [ -n "$phpPid" ];then
        echo -e "$Info ${light_geen}PHP $phpVer安装成功${nocolor}
-------------------------------------------------------
PHP安装位置：$phpPath
如果nginx/apache添加了PHP模块支持，请在重启nginx或apache后，
访问 http://[IP]:[Port]/phpinfo.php 检查PHP支持
如有任何PHP扩展支持问题，请参考帮助或者自行百度
--------------------------------------------------------"
    else
        echo -e "$Error PHP $phpVer 安装失败"
    fi
    anykeyback
}

